<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="code">
        <el-input
            v-model="queryParams.code"
            placeholder="请输入单据编号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="源单据编号" prop="sourceCode">
        <el-input
            v-model="queryParams.sourceCode"
            placeholder="请输入源单据编号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['caigou:gysbj:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['caigou:gysbj:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['caigou:gysbj:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['caigou:gysbj:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="gysbjList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
<!--      <el-table-column label="主键Id" align="center" prop="id"/>-->
      <el-table-column label="单据编号" align="center" prop="code" width="200px" fixed/>
      <el-table-column label="源单据编号" align="center" prop="sourceCode" width="200"/>
      <el-table-column label="供应商" align="center" prop="supplierName" width="200"/>
      <el-table-column label="单据阶段" align="center" prop="docStage">
        <template slot-scope="scope">
          <span v-if="scope.row.docStage == 0">编制完</span>
          <span v-if="scope.row.docStage == 1">执行中</span>
          <span v-if="scope.row.docStage == 2">执行完</span>
        </template>
      </el-table-column>
      <el-table-column label="审核结果" align="center" prop="approvalResult"/>
      <el-table-column label="是否生效" align="center" prop="isEffect">
        <template slot-scope="scope">
          <span v-if="scope.row.isEffect == 0 || scope.row.isEffect == undefined || scope.row.isEffect == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否关闭" align="center" prop="isClose">
        <template slot-scope="scope">
          <span v-if="scope.row.isClose == 0 || scope.row.isClose == undefined || scope.row.isClose == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" prop="isCancel">
        <template slot-scope="scope">
          <span v-if="scope.row.isCancel == 0 || scope.row.isCancel == undefined || scope.row.isCancel == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy"/>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px" fixed="right">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['caigou:gysbj:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['caigou:gysbj:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />


    <!-- 添加或修改供应商报价对话框 -->
    <el-dialog
        :title="title"
        :visible.sync="open"
        width="1300px"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" inline>
        <el-form-item label="单据编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入单据编号" readonly/>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <!--          <el-input v-model="form.code" placeholder="请输入单据编号"  readonly/>-->
          <el-select v-model="form.supplierId" placeholder="请选择">
            <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.supName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购询价单" prop="sourceCode" label-width="100px">
          <el-input v-model="form.sourceCode" placeholder="询价单" readonly></el-input>
        </el-form-item>
        <el-form-item>
          <el-button plain @click="selectBuyAsk">选择</el-button>
        </el-form-item>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="询价单明细" name="first">
            <el-table
                :data="buyAskList"
                style="width: 100%">
              <el-table-column
                  prop="id"
                  label="主键"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="code"
                  label="单据编号"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="createBy"
                  label="创建人">
              </el-table-column>
              <el-table-column
                  prop="docDate"
                  label="单据日期">
              </el-table-column>
            </el-table>

            <el-button plain icon="el-icon-arrow-right" @click="addBuyAskGoodsForGybjGoods">添加</el-button>
            <el-table :data="buyAskListGoods"
                      @selection-change="handleSelectionChangeBuyAskGoodsList">
              <el-table-column
                  type="selection"
                  width="55"
                  :selectable="checkSelectable">
              </el-table-column>
              <el-table-column
                  prop="id"
                  label="主键"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="proCode"
                  label="编码"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="proName"
                  label="名称"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="typeName"
                  label="类型">
              </el-table-column>
              <el-table-column
                  prop="number"
                  label="数量">
              </el-table-column>
              <el-table-column
                  prop="unitName"
                  label="单位">
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="明细" name="second">
            <el-button plain icon="el-icon-arrow-left" @click="addGybjGoodsForBuyAskGoods">移除</el-button>

            <el-table :data="gybjGoodsList" @selection-change="handleSelectionChangeGybjGoodsList">

              <el-table-column
                  type="selection"
                  width="55" >
              </el-table-column>
              <el-table-column
                  prop="id"
                  label="主键"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="proCode"
                  label="编码"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="proName"
                  label="名称"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="typeName"
                  label="类型">
              </el-table-column>
              <el-table-column
                  prop="number"
                  label="数量">
              </el-table-column>
              <el-table-column
                  prop="unitName"
                  label="单位">
              </el-table-column>
              <el-table-column
                  prop="price"
                  label="含税单价">
                <template slot-scope="scope">
                  <MyNumberInput :point="2" :max="99999" placeholder="请输入金额" v-model.number="scope.row.price"></MyNumberInput>
<!--                  <input  type="number" v-model="scope.row.price" placeholder="请输入扣分" οnkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"/>-->
<!--                  <el-input v-model="scope.row.price"  oninput ="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入(整数或者小数)金额" />-->
                </template>
              </el-table-column>
              <el-table-column
                  prop="tax"
                  label="税率">
                <template slot-scope="scope">
<!--                  <el-input v-model="scope.row.tax"  oninput ="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入(整数或者小数)金额" />-->
                  <el-select v-model="scope.row.tax" placeholder="请选择">
                    <el-option
                      v-for="item in [{value:0.00,label:'0%'},{value:0.03,label:'3%'},{value:0.05,label:'5%'}]"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </template>

              </el-table-column>

              <el-table-column
                label="含税金额">
                <template slot-scope="scope">
                  <el-input :value="scope.row.number * scope.row.price "  readonly />

                </template>
              </el-table-column>
            </el-table>

          </el-tab-pane>

        </el-tabs>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    选择采购询价单弹窗-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisibleSelectBuyAsk"
        width="1000px"
        :close-on-click-modal="false"
        :close-on-press-escape="false">
      <SelectBuyAsk ref="selectBuyAskRef"/>

      <span slot="footer" class="dialog-footer">
              <el-button @click="cancelSelectBuyAsk">取 消</el-button>
             <el-button type="primary" @click="sureSelectBuyAsk">确 定</el-button>
             </span>
    </el-dialog>
  </div>
</template>

<script>
import {listGysbj, getGysbj, delGysbj,delGysbjPlus, addGysbj, updateGysbj, updateGysbjPlus,addGysbjPlus, getGysbjPlus} from "@/api/caigou/gysbj";
import {getCaigouxunjiaInfo, getCaigouxunjiaInfoByCode} from '@/api/caigou/caigouxunjia';
import {listSupplies} from '@/api/basedata/supplies';
import SelectBuyAsk from "@/views/caigou/gysbj/SelectBuyAsk.vue";
import MyNumberInput from "@/views/caigou/gysbj/MyNumberInput.vue";
export default {
  name: "Gysbj",
  components: {SelectBuyAsk,MyNumberInput},
  data() {
    return {
      //被选中的供应报价商品
      multipleSelectionGybjGoods:[],
      //被选中的采购询价商品
      multipleSelectionBuyGoodsList:[],
      //明细数组
      gybjGoodsList: [],
      //采购询价单商品信息
      buyAskListGoods: [],
      //采购询价单信息
      buyAskList: [],
      activeName: 'second',
      //选择采购询价单的弹窗
      dialogVisibleSelectBuyAsk: false,
      //供应商数组
      supplierList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商报价表格数据
      gysbjList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        sourceCode: null,
        docStage: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          {required: true, message: "单据编号不能为空", trigger: "blur"}
        ],
        supplierId: [
          {required: true, message: "供应商不能为空", trigger: "blur"}
        ],
        sourceCode: [
          {required: true, message: "请选择询价单", trigger: "blur"}
        ]
      }
    };
  },
  computed:{

  },
  created() {
    this.getList();
  },
  methods: {

    addGybjGoodsForBuyAskGoods(){
        this.buyAskListGoods.forEach(good=>{
          this.multipleSelectionGybjGoods.forEach(v=>{
            if (good.id == v.id){
              good.status = 0;
              this.gybjGoodsList.pop(good);
            }
          })
        })
    },
    addBuyAskGoodsForGybjGoods(){
      this.gybjGoodsList = [];
      this.buyAskListGoods.forEach(good=>{
        this.multipleSelectionBuyGoodsList.forEach(v=>{
          if (good.id == v.id){
            good.status = 1;
            this.gybjGoodsList.push(good);
          }
        })
      })
    },
    // 判断能否勾选
    checkSelectable(row){
      return row.status == 0;
    },
    //供应报价明细勾选
    handleSelectionChangeGybjGoodsList(val){
      this.multipleSelectionGybjGoods = val;
    },
    // 采购申请明细勾选
    handleSelectionChangeBuyAskGoodsList(val) {
      this.multipleSelectionBuyGoodsList = val;
    },
    getBuyAskGoodsList(id) {

    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    cancelSelectBuyAsk(){
      this.form.sourceCode = '';
      this.dialogVisibleSelectBuyAsk = false;
    },
    sureSelectBuyAsk() {
      let currentBuyAsk = this.$refs.selectBuyAskRef.returnBuyAsk();
      if (currentBuyAsk == undefined || currentBuyAsk == null) {
        this.$message.warning('请选择采购询价单')
        return;
      }
      this.form.sourceCode = currentBuyAsk.code;
      console.log(currentBuyAsk);
      this.buyAskList = [];
      this.buyAskList.push(currentBuyAsk)
      // this.getCaigouxunjiaInfoByCode(currentBuyAsk.code);
      getCaigouxunjiaInfoByCode(currentBuyAsk.code).then(res => {
        console.log(res);
        res.data.goodsList.forEach(goods => {
          res.data.idAndNumberList.forEach(idNumber => {
            if (idNumber.id == goods.id) {
              goods.number = idNumber.number;
            }
          })
          goods.price = 0;
          goods.tax = 0;
          goods.status = 0;

        })
        // console.log(res.data.goodsList);
        this.buyAskListGoods = res.data.goodsList
        this.gybjGoodsList = [];
        // this.gybjGoodsList = [];
        // res.data.goodsList.forEach(goods => {
        //   this.gybjGoodsList.push({...goods, price: 0, tax: 0,status:0});
        // })

      })
      this.dialogVisibleSelectBuyAsk = false;
    },
    // 选择采购询价单
    selectBuyAsk() {
      this.dialogVisibleSelectBuyAsk = true;
    },
    /** 查询供应商报价列表 */
    getList() {
      this.loading = true;
      listGysbj(this.queryParams).then(response => {
        this.gysbjList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: 'GYBJ-' + Date.now(),
        sourceCode: null,
        docStage: null,
        supplierId: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        isDel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 新增初始化数据
    initBaseData() {
      //获取所有供应商
      listSupplies().then(res => {
        this.supplierList = res.rows
      })
      //明细数组
      this.gybjGoodsList = [];
      //采购询价单商品信息
      this.buyAskListGoods = [];
      //采购询价单信息
      this.buyAskList = [];
      this.gybjGoodsList = [];
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商报价";
      // this.initBaseData();
      this.initBaseData();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.initBaseData();
      getGysbjPlus(id).then(response => {
        console.log('getGysbjPlus',response)
        this.form = response.data.buySupplies;
        this.gybjGoodsList = response.data.buySuppliesPrices;
        let arr = [];
        this.gybjGoodsList.forEach(item=>{
          item.tax = item.tax
          arr.push(item);
        })
        this.gybjGoodsList = arr;
        // this.getCaigouxunjiaInfoByCode(this.form.sourceCode);
        // getCaigouxunjiaInfoByCode(this.form.sourceCode).then(res => {
        //   console.log(res);
        //   res.data.goodsList.forEach(goods => {
        //     res.data.idAndNumberList.forEach(idNumber => {
        //       if (idNumber.id == goods.id) {
        //         goods.number = idNumber.number;
        //       }
        //     })
        //     goods.price = 0;
        //     goods.tax = 0;
        //     goods.status = 0;
        //
        //   })
        //   this.buyAskListGoods = res.data.goodsList
        //
        // })
        // sourceCode
        this.open = true;
        this.title = "修改供应商报价";
      });

    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.gybjGoodsList);
      let goodsList = [];
      this.gybjGoodsList.forEach( item=>{
        goodsList.push({
          goodsId:item.id,
          buySuppliesCode:this.form.code,
          number:item.number,
          price:item.price,
          tax:item.tax
        })
        }
      )
      if (goodsList.length==0){
        this.$modal.msgWarning('请添加明细');
        return;
      }
      console.log('aaa',goodsList)
      console.log(this.form);

      // return;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.updateBy = this.$store.getters.name;
            updateGysbjPlus({
              "buySupplies":this.form,
              "buySuppliesPrices":goodsList
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createBy = this.$store.getters.name;
            addGysbjPlus({
              "buySupplies":this.form,
              "buySuppliesPrices":goodsList
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除供应商报价编号为"' + ids + '"的数据项？').then(function () {
        return delGysbjPlus(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('caigou/gysbj/export', {
        ...this.queryParams
      }, `gysbj_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
